import base64
from PIL import Image
from io import BytesIO
import cv2
import os
import random
import pyautogui
import time


# 滑块的缺口距离识别
def get_distance():
    # 读取背景图片和模板图片
    background = cv2.imread('img/target.png', 0)
    template = cv2.imread('img/target2.png', 0)
    # 进行预处理，如去噪和边缘增强
    template = cv2.Canny(template, 300, 500, 3)
    # 使用算法进行匹配
    res = cv2.matchTemplate(background, template, cv2.TM_CCOEFF)
    print(cv2.minMaxLoc(res))
    min_val, max_val, min_loc, max_loc = cv2.minMaxLoc(res)
    top_left = max_loc
    distance = top_left[0] * 344 / 552
    return distance

# get_distance()


def saveimg(page):
    iframe = page.get_frame('t:iframe')
    iframe('#captcha-verify_img_slide').save(path="./img", name="target2.png", rename=False)
    iframe.ele('#captcha_verify_image').save(path="./img", name="target.png", rename=False)
    return iframe

def ease_out_cubic(t):
    # 缓动函数 - 先快后慢
    return 1 - (1 - t) ** 3


def move_with_easing(page, end_x, end_y, duration):
    start_time = time.time()
    numbers_x = [0]
    numbers_y = [0]
    while True:
        elapsed_time = time.time() - start_time
        if elapsed_time >= duration:
            page.actions.release()
            # 动画结束
            break
        # 计算当前时间对应的缓动值
        t = elapsed_time / duration
        easing_value = ease_out_cubic(t)
        # 根据缓动值计算当前位置
        current_x = end_x * easing_value
        current_y = end_y * easing_value
        num_x = round(current_x - numbers_x[-1], 1)
        num_y = round(current_y - numbers_y[-1], 1)
        page.actions.move(num_x, num_y, 0)
        numbers_x.append(current_x)
        numbers_y.append(current_y)


def slider_img(page):
    while page.get_frame('t:iframe', timeout=3):
        iframe = saveimg(page)
        x = get_distance()
        print(x)
        btn_slide = iframe('.captcha-slider-btn')
        iframe.actions.hold(btn_slide)
        move_with_easing(iframe, x, 0, 2)
        page.wait(3)

